package com.xmut.rc.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xmut.rc.common.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author ASUS
 * @Version v1.0
 * @InterfaceName: CommonWebAPI
 * @Description:
 * @Date: 2021/10/28 11:41
 */
@Api(tags = "公共接口")
@RestController
@RequestMapping("/system/common")
@CrossOrigin
@Slf4j
public class CommonController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private String bizPath = "D:/pictures/";
    private ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping(value = "/upload-file")
    public Result<?> uploadFile(MultipartFile file) {
        //文件原始名称
        String original = file.getOriginalFilename();
        //随机不重复UUID
        String fileName = UUID.randomUUID().toString();
        //文件后缀
        String fileType = original.substring(original.lastIndexOf("."));
        String newName = fileName + fileType;
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(bizPath + newName));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return Result.error("图片上传失败:" + e.getMessage());
        } finally {
        }
        HashMap fileInfo = new HashMap();
        newName = "/system/common/static/"+newName;
        fileInfo.put("path", newName);
        return Result.OK(fileInfo);
    }

    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

    @GetMapping(value = "/static/**")
    public void view(HttpServletRequest request, HttpServletResponse response) {
        // ISO-8859-1 ==> UTF-8 进行编码转换
        String imgPath = extractPathFromPattern(request);
        if(StringUtils.isEmpty(imgPath) || imgPath=="null"){
            return;
        }
        // 其余处理略
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            imgPath = imgPath.replace("..", "").replace("../","");
            if (imgPath.endsWith(",")) {
                imgPath = imgPath.substring(0, imgPath.length() - 1);
            }
            String filePath = bizPath + File.separator + imgPath;
            File file = new File(filePath);
            if(!file.exists()){
                response.setStatus(404);
                throw new RuntimeException("文件["+imgPath+"]不存在..");
            }
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
            inputStream = new BufferedInputStream(new FileInputStream(filePath));
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (IOException e) {
            log.error("预览文件失败" + e.getMessage());
            response.setStatus(404);
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @DeleteMapping(value = "/remove-file/{fileName}")
    public Result<?> deleteFile(@PathVariable String fileName) {
        try {
            FileUtils.delete(new File(bizPath + fileName));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return Result.error("图片移除失败:" + e.getMessage());
        } finally {
        }
        return Result.OK(fileName);
    }
}
